
import { Injectable } from '@angular/core';
import { Observable, Subject, of } from 'rxjs';
import { map, catchError, tap  } from 'rxjs/operators';

import { HttpHeaders, HttpParams, HttpClient } from '@angular/common/http';

import { User } from '../models/User';
import { Department } from '../models/Department';
import { environment } from '../environments/environment';

@Injectable()
export class AuthService {



    user: User;
    // store the URL so we can redirect after logging in
    redirectUrl: string;

    private baseUrl =  environment.apiUrl + 'api/user';

    userSource = new Subject<User>();
    userObservable = this.userSource.asObservable();

    constructor(
        private http: HttpClient
    ) {

    }

    login(user: User): Observable<{user: User, department: Department, success: boolean}> {
        return this.http.post<{user: User, department: Department, success: boolean}>(this.baseUrl + '/login', user).pipe(tap((res) => {
            if (res.success) {
                this.userSource.next(res.user);
            }
        }));
    }

    logout(): Observable<any> {
        this.user = null;
        this.userSource.next(null);
        return this.http.get(this.baseUrl + '/logout');
    }

    getCurrent(): Observable< {res: User, success: boolean}> {
        return this.http.get<{res: User, success: boolean}>(this.baseUrl + '/getuserbysession').pipe(map(res => {
            if (res.success) {
              this.user = res.res;
              this.userSource.next(this.user);
            }
            return res;
        }));
    }


}
